<!-- eslint-disable prettier/prettier -->
<!-- eslint-disable vue/html-indent -->
<template>
    <div id="customerDetail" class="customer-detail">
        <div class="left-module">
            <Company
                v-if="isCompany"
                :cust-status="state.custStatus"
                :base-info="state.baseInfo"
                :tag-info="state.tagInfo"
                :body-info="state.bodyInfo"
                :touch-mode-list="state.touchModeList"
                :cust_corp_info="state.cust_corp_info"
                @refresh="initFun"
                @submit="getCustList" />
            <BasicInfo
                v-else
                :interact-points="state.interact_points"
                :wx-external-userid="wx_external_userid"
                :cust-status="state.custStatus"
                :base-info="state.baseInfo"
                :tag-info="state.tagInfo"
                :body-info="state.bodyInfo"
                :touch-mode-list="state.touchModeList"
                :member-base-info="memberInfo"
                @refresh="initFun" />
            <!-- 会员信息 -->
            <div v-if="memberInfo.member_status == 1" class="customer-card">
                <div class="member-info-box">
                    <div class="member-info-title">会员信息</div>
                    <div class="member-info-cell">
                        <div class="cell-label">会员ID：</div>
                        <div class="cell-value">{{ memberInfo.member_no }}</div>
                    </div>
                    <div class="member-info-cell">
                        <div class="cell-label">入会时间：</div>
                        <div class="cell-value">{{ memberInfo.join_time }}</div>
                    </div>
                    <div class="member-info-cell">
                        <div class="cell-label">会员等级：</div>
                        <div class="cell-value">
                            {{ memberInfo.member_level_name }} <span @click="handlerGradeChange">变更记录</span>
                        </div>
                    </div>
                    <div class="member-info-cell">
                        <div class="cell-label">会员权益：</div>
                        <div>
                            <el-tag
                                v-for="(item, index) in memberInfo.priority"
                                :key="index"
                                class="cell-label-tag"
                                size="small">
                                {{ item.priority_val }}
                            </el-tag>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 收货地址 -->
            <HarvestAddress />
            <!-- 最近浏览商品 -->
            <RecentlyBrowsed />
        </div>
        <div class="right-module">
            <div class="journey-box">
                <div class="title-box">
                    <span class="lable-name">基础信息</span>
                    <div>
                        <el-button v-auth="'ADD_EDIT'" plain @click="openAddCustomer">编辑</el-button>
                        <el-button v-if="state.baseInfo.cust_assign_status == 2" plain @click="customerReturnFun">
                            退回客户
                        </el-button>
                        <el-button v-show="state.baseInfo.cust_assign_status == 2" plain @click="setProcetFun">
                            {{ !state.baseInfo.is_protected ? '设为保护' : '取消保护' }}
                        </el-button>
                        <el-button v-auth="'RE_ASSIGN'" plain @click="openDepart">
                            {{
                                state.baseInfo.cust_assign_status == 0
                                    ? '分配员工'
                                    : state.baseInfo.cust_assign_status == 1
                                    ? '重新分配'
                                    : '客户转交'
                            }}
                        </el-button>
                        <el-button v-auth="'ADD_BUSINESS'" plain @click="AddBusinessOpt">添加商机</el-button>
                        <el-button v-auth="'ADD_FOLLOW_UP'" type="primary" @click="showAddFollowFun">
                            添加跟进
                        </el-button>
                    </div>
                </div>
                <div class="base-info">
                    <el-scrollbar>
                        <div class="step-box">
                            <div v-for="(item, index) in stepList" :key="item.id">
                                <div :class="`icon-box ${index <= nowStageIndex ? 'active' : ''}`">
                                    <el-icon
                                        v-if="index + 1 <= nowStageIndex"
                                        style="color: white; font-size: 20px; margin-top: 5px">
                                        <check />
                                    </el-icon>
                                    {{ index + 1 <= nowStageIndex ? '' : index + 1 }}
                                </div>
                                <span>{{ item.name }}</span>
                            </div>
                        </div>
                    </el-scrollbar>
                    <div class="change-btn">
                        <el-dropdown>
                            <el-button class="add_btn" type="primary">变更阶段</el-button>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item
                                        v-for="item in stepList"
                                        :key="item.id"
                                        @click="handleStage(item)">
                                        {{ item.name }}
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </div>
                </div>
                <!-- <div class="step-box"> </div> -->
            </div>
            <!-- 电商数据板 -->
            <!-- <RetailersDataBoard v-if="isShowShop" :data="state.retailersDta" /> -->
            <DataOverview
                v-if="state.shop_status"
                v-loading="isShopLoading"
                title="电商数据总览"
                :list="state.shop_info" />
            <DataOverview v-if="state.business_show" title="商机数据总览" :list="state.business_num" />
            <DataOverview title="客户数据总览" :list="state.data_census" />
            <!-- <DataBoard :data="state.dataCensus" /> -->
            <!-- 客户动态 -->
            <Dynamic :step-list="stepList" :is-show-shop="isShowShop" :is-company="isCompany" />
            <!-- 最近关注 -->
            <Follow />
            <!-- 添加员工 -->
            <StaffInfo
                v-if="(!isCompany && wx_external_userid) || isCompany"
                :is-company="isCompany"
                :cust-list="custList"
                :wx-external-userid="wx_external_userid"
                :step-list="stepList" />
            <!-- 所在群 -->
            <GroupInfo
                v-if="(!isCompany && wx_external_userid) || isCompany"
                :is-company="isCompany"
                :cust-list="custList"
                :wx-external-userid="wx_external_userid" />
            <!-- 活动参与情况 -->
            <ActivityTable ref="ActivityTableRef" />

            <!-- <AddCustomer ref="AddCustomerRef" :sourceArr="sourceArr" @save="getListFun" /> -->
            <!-- 添加跟进 -->
            <AddFollow ref="AddFollowRef" @save="initFun" />

            <!-- 部门人员弹框 -->
            <ZWDepart ref="DepartRef" :is-local="true" @submit="getZWDepartData" />
            <!-- 编辑 -->
            <AddCustomer ref="AddCustomerRef" v-model="addCustomerVisible" @submit="getListFun" />
            <!--无效原因弹框-->
            <Dialog :app-dialog="appDialog">
                <div style="margin-top: 14px; font-weight: 600">您确定要变更该客户为无意向客户吗？</div>
                <el-select v-model="params.invalid_id" style="margin: 24px 0" placeholder="请选择无效原因">
                    <el-option
                        v-for="item in reasonLists"
                        :key="item.name"
                        :value="item.id"
                        :label="item.name"></el-option>
                </el-select>
            </Dialog>
        </div>
        <GradeChangeDetails ref="gradeChangeDetailsRef" />
    </div>
</template>

<script setup lang="ts">
import HarvestAddress from './components/HarvestAddress';
import RecentlyBrowsed from './components/RecentlyBrowsed';
import DataOverview from './components/DataOverview';
import ZWDepart from '@/components/ZWDepart.vue';
import router from '@/router';
import { onMounted, reactive, ref, watch, nextTick, computed } from 'vue';
import { useRoute } from 'vue-router';
import { sourceList, stageList, changeStage, reasonList } from '../../configure/api';
import {
    getCustomerDetail,
    batchAssignStaff,
    customerReturn,
    customerProtectNum,
    customerProtect,
    customerShopInfo
} from '@/api/customerCenter';
import { getMemberBaseInfo } from '@/api/customer/manage/list';
import { ElMessage, ElMessageBox } from 'element-plus';
import { IsNotEmpty, getSetionId } from '@/utils/utils';
import ActivityTable from './components/ActivityTable.vue';
// import AddCustomer from '../components/AddCustomer.vue'
import AddCustomer from '@/components/customerCenter/AddCustomer.vue';
import AddFollow from '../components/AddFollow.vue';
import BasicInfo from './components/BasicInfo.vue';
import Company from './components/Company.vue';
import DataBoard from './components/DataBoard.vue';
import Dynamic from './components/Dynamic.vue';
import Follow from './components/Follow.vue';
import StaffInfo from './components/StaffInfo.vue';
import GroupInfo from './components/GroupInfo.vue';
import RetailersDataBoard from './components/RetailersDataBoard.vue';
import Dialog from '@/components/Dialog.vue';
import GradeChangeDetails from './components/GradeChangeDetails.vue';

const ActivityTableRef = ref(null);
const AddCustomerRef = ref(null);
const AddFollowRef = ref(null);
const DepartRef = ref(null);
const sourceArr = ref([]);
const stepList = ref([]);
const nowStageIndex = ref(0); //当前处于那个阶段
const isCompany = ref(false);
const addCustomerVisible = ref(false);
const custList = ref([]);
const route = useRoute();
const wx_external_userid = ref(0);
const gradeChangeDetailsRef = ref<any>(null);
const isShowShop = computed(() => {
    return state.retailersDta.shop_status == 1;
});
const memberInfo = reactive<any>({
    member_status: '',
    member_no: '',
    member_level: '',
    member_level_name: '',
    growth_val: '',
    available_points: '',
    join_time: '',
    priority: [],
    member_distribute_name: ''
});
const params = reactive({
    cust_id: '',
    cust_stage_id: '',
    invalid_id: ''
});
const reasonLists = ref([]);

const isShopLoading = ref(false);

// 取消
const cancelHandel = () => {
    appDialog.visible = false;
};
//确定
const submitHandel = () => {
    if (!params.invalid_id) {
        ElMessage.error('请选择无效原因');
        return;
    } else {
        changeStage(params).then((res: any) => {
            appDialog.visible = false;
            initFun();
            ElMessage.success('变更阶段成功');
        });
    }
};
const appDialog = reactive({
    visible: false,
    title: '提示',
    width: '400px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定'
});
//变更阶段
const handleStage = (val: any) => {
    params.cust_id = route.query?.id;
    params.cust_stage_id = val.id;
    if (val.flag == 2) {
        getReasonList();
        appDialog.visible = true;
    } else {
        changeStage(params).then((res: any) => {
            initFun();
            ElMessage.success('变更阶段成功');
        });
    }
};
//获取无效原因列表
const getReasonList = () => {
    reasonList().then((res: any) => {
        reasonLists.value = res;
    });
};
//客户联系人
const getCustList = (val?: any) => {
    const params = [{ name: '全部', cust_id: -1 }, ...val];
    custList.value = params;
};

// 获取客户来源字典
const sourceListFun = () => {
    sourceList({ page: 1, page_size: 999 }).then((r: any) => {
        r.data = r.data || [];
        const arr = [{ name: '全部', id: -1 }];
        r.data.forEach((it: any) => {
            if (it.status == 1) {
                arr.push(it);
            }
        });
        sourceArr.value = arr;
    });
};

// 阶段
const getTableList = () => {
    stageList({ page: 1, page_size: 999 }).then((r: any) => {
        r = r || [];
        if (state.baseInfo.current_stage_id) {
            const index = r.findIndex((it: any) => {
                return it.id == state.baseInfo.current_stage_id;
            });
            nowStageIndex.value = index;
        } else {
            nowStageIndex.value = 0;
        }
        stepList.value = r;
    });
};

const state = reactive({
    shop_status: 0, // 店铺应用是否开启 0-关闭 1-开启
    business_show: 0, // 商机总数
    shop_info: [], // 电商数据总览
    business_num: [], // 商机数据总览
    data_census: [], // 客户数据总览
    wx_external_userid: '',
    custStatus: 0,
    baseInfo: {},
    tagInfo: [],
    bodyInfo: [],
    dataCensus: {},
    retailersDta: {},
    touchModeList: {},
    protectInfo: {}, //保护次数
    cust_corp_info: {} //企业信息
});

const customerProtectNumFun = () => {
    customerProtectNum().then((r: any) => {
        state.protectInfo = r;
    });
};

/**
 * @description: 获取客户详情电商数据
 * @return {*}
 */
const getShopInfo = async () => {
    isShopLoading.value = true;
    const shop_info = await customerShopInfo({ cust_id: route.query.id });
    state.shop_status = shop_info?.shop_status;
    state.shop_info = [
        {
            name: '应付金额(元)',
            value: shop_info?.total_payable_amount || '0',
            tips: '客户已支付订单（去除退款订单）中，包括优惠减免金额及优惠抵扣金额，客户应支付的金额，包含运费、税费'
        },
        {
            name: '实付金额(元)',
            value: shop_info?.total_order_amount || '0',
            tips: '客户已支付订单（去除退款）中，在扣除优惠减免金额及优惠抵扣金额后，客户实际支付的金额，包含运费、税费'
        },
        { name: '支付单数', value: shop_info?.total_order_num || '0', tips: '该客户已支付的订单总数（去除退款订单）' },
        {
            name: '商品件数',
            value: shop_info?.total_order_product_num || '0',
            tips: '该客户已支付的订单（去除退款订单）中，购买商品的总件数'
        },
        {
            name: '客单价(元)',
            value: shop_info?.avg_order_amount || '0',
            tips: '该客户平均每笔订单的金额（应付金额/支付单数）'
        },
        {
            name: '客单件(件)',
            value: shop_info?.avg_order_num || '0',
            tips: '该客户平均每笔订单的商品件数（商品件数/支付单数）'
        },
        { name: '今日实付金额(元)', value: shop_info?.today_order_amount || '0' },
        { name: '今日购买商品件数', value: shop_info?.today_order_num || '0' },
        {
            name: '复购次数',
            value: shop_info?.repurchase_num || '0',
            tips: '支付单数为0，复购次数为0；支付单数>0时，复购次数=支付单数-1'
        }
    ];
    state.retailersDta = shop_info;
    isShopLoading.value = false;
};

// 初始化
const initFun = () => {
    customerProtectNumFun();
    getShopInfo();
    // 获取详情数据
    getCustomerDetail({ cust_id: route.query.id }).then((res: any) => {
        state.business_show = res.business_num.business_num;
        state.business_num = [
            { name: '商机总金额(元)', value: res.business_num.business_total_money },
            { name: '已赢单金额(元)', value: res.business_num.business_win_order_money },
            { name: '预计赢单金额(元)', value: res.business_num.pre_business_win_order_money },
            { name: '已输单金额(元)', value: res.business_num.lost_order_money },
            { name: '商机总数', value: res.business_num.business_num },
            { name: '赢单商机数', value: res.business_num.business_win_num },
            { name: '输单单商机数', value: res.business_num.business_lost_num }
        ];
        state.data_census = [
            { name: '可联系企微员工数', value: res.data_census.add_qw_num },
            { name: '累计跟进次数', value: res.data_census.follow_num },
            { name: '累计微信聊天次数', value: res.data_census.message_count },
            { name: '累计互动次数', value: res.data_census.frequency_num },
            { name: '企微群聊数', value: res.data_census.group_num }
            // { name: '抖音点赞数', value: res.data_census.douyin_likes },
            // { name: '抖音评论数', value: res.data_census.douyin_comments },
            // { name: '抖音私信数', value: res.data_census.douyin_message }
        ];
        res.base_info.current_stage_id = res.current_stage_id || '';
        res.base_info.id = route.query.id;
        res.base_info.cust_assign_status = res.cust_assign_status || 0;
        res.base_info.is_protected = res.is_protected || 0;
        res.base_info.assign_employees = res.assign_employees || {};
        res.base_info.cust_baseinfo = res.cust_baseinfo;
        wx_external_userid.value = res.wx_external_userid;
        state.wx_external_userid = res.wx_external_userid;
        state.custStatus = res.custStatus;
        state.baseInfo = res.base_info;
        state.tagInfo = res.tag_info;
        state.bodyInfo = res.body_info.filter((item: any) => item.name);
        // const assign = { name: '企微手机号', val: res.follow_mobile, order: null, type: 'qwPhone' }
        const index = state.bodyInfo.findIndex((item: any) => item.name == '备用手机号');
        let phoneArr = [];
        if (state.bodyInfo[index] && state.bodyInfo[index].val != null && state.bodyInfo[index].val.length != 0) {
            phoneArr = state.bodyInfo[index].val.split(',');
        }
        if (res.follow_mobile.length != 0) {
            res.follow_mobile.map((item: any) => {
                phoneArr.unshift({ item: item, isQw: 1 });
            });
        }
        if (state.bodyInfo[index]) {
            state.bodyInfo[index].val = phoneArr.length ? phoneArr : '';
        }

        // state.bodyInfo.splice(index - 1, 1, res.follow_mobile)
        state.dataCensus = res.data_census;
        state.touchModeList = res.touch_mode_list;
        state.cust_corp_info = res.cust_corp_info;
        state.interact_points = res.interact_points;
        getTableList();
    });
};
// 回退客户
const customerReturnFun = () => {
    ElMessageBox.confirm(
        '退回客户后，您将不能跟进该客户，其他员工将可认领该客户，您确定要将该客户退回吗？',
        '退回客户',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
        }
    )
        .then(() => {
            if (!route.query.id) {
                ElMessage.error('当前数据异常，请稍后再试');
                initFun();
                return;
            }
            customerReturn({ cust_id: route.query.id }).then((r: any) => {
                initFun();
            });
        })
        .catch();
};
// 设为保护
const setProcetFun = () => {
    if (state.protectInfo.current_portect_num >= state.protectInfo.max_protect_num) {
        ElMessage.error('当前设置保护次数为0,无法保护');
        return;
    }
    if (!state.baseInfo.is_protected) {
        ElMessageBox.confirm(
            `您还有${
                state.protectInfo.max_protect_num - state.protectInfo.current_portect_num
            }个设置保护客户的名额，设为保护后，客户将不会被系统回收。您确定要将该客户设为保护吗？`,
            'Warning',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                title: '设为保护'
            }
        ).then(() => {
            if (!route.query.id) {
                ElMessage.error('当前数据异常，请稍后再试');
                initFun();
                return;
            }
            customerProtect({ cust_id: route.query.id, status: state.baseInfo.is_protected ? 2 : 1 }).then((r: any) => {
                ElMessage.success('设置保护成功');
                initFun();
            });
        });
        return;
    } else {
        ElMessageBox.confirm(`您确定取消保护吗？`, 'Warning', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            title: '取消保护'
        }).then(() => {
            if (!route.query.id) {
                ElMessage.error('当前数据异常，请稍后再试');
                initFun();
                return;
            }
            customerProtect({ cust_id: route.query.id, status: state.baseInfo.is_protected ? 2 : 1 }).then((r: any) => {
                ElMessage.success('取消保护成功');
                initFun();
            });
        });
        return;
    }
};
// 添加客户
// const openAddCustomer = () => {
//   AddCustomerRef.value.drawerData.userInfo = { id: route.query.id }
//   AddCustomerRef.value.drawerData.controlType = 'edit'
//   AddCustomerRef.value.drawerData.show = true
// }
//
const openAddCustomer = () => {
    AddCustomerRef.value.drawerData.userInfo = { id: route.query.id, type: route.query.type };
    AddCustomerRef.value.drawerData.controlType = 'edit';
    addCustomerVisible.value = true;
};
// 添加跟进
const showAddFollowFun = (val: any) => {
    AddFollowRef.value.drawerData.userInfo = state.baseInfo;
    AddFollowRef.value.drawerData.show = true;
    AddFollowRef.value.followId = route.query.id;
};

//打开新建选择人
const openDepart = () => {
    DepartRef.value.selectedMember = IsNotEmpty(state.baseInfo?.assign_employees)
        ? [state.baseInfo.assign_employees]
        : [];
    DepartRef.value.multiple = false;
    DepartRef.value.departVisble = true;
    DepartRef.value.title = '选择员工';
};
// 添加商机
const AddBusinessOpt = () => {
    router.push(`/salesleads/salesmanagement/business/create?customer=${route.query.id}`);
};

// 获取当前选中的员工的数据
const getZWDepartData = (val: any, flag?: boolean) => {
    if (flag) return;
    if (val.length == 0) {
        ElMessage.warning('请选择员工');
        return;
    }
    batchAssignStaff({
        customer_list: [route.query?.id],
        work_user_list: getSetionId('id', val)
    }).then((r: object) => {
        initFun();
    });
};

const handlerGradeChange = () => {
    gradeChangeDetailsRef.value.state.searchParams.member_no = '';
    gradeChangeDetailsRef.value.state.searchParams.member_no = memberInfo.member_no;
    gradeChangeDetailsRef.value.appDialog.visible = true;
};

const initMemberInfo = async () => {
    const params = {
        cust_id: route.query.id
    };
    const res = await getMemberBaseInfo(params);
    memberInfo.member_status = res.member_status;
    memberInfo.member_no = res.member_no;
    memberInfo.member_level = res.member_level;
    memberInfo.member_level_name = res.member_level_name;
    memberInfo.growth_val = res.growth_val;
    memberInfo.available_points = res.available_points;
    memberInfo.join_time = res.join_time;
    memberInfo.priority = res.priority;
    memberInfo.member_distribute_name = res.member_distribute_name || '';
    memberInfo.points = res.points;
    memberInfo.level_info = res.level_info;
};

onMounted(() => {
    isCompany.value = route.query?.type == 2; // 企业
    initFun();
    if (route.query?.type == 1) {
        initMemberInfo();
    }
});

watch(
    () => router.currentRoute.value.path,
    toPath => {
        document.body.scrollTop = 0;
        document.documentElement.scrollTop = 0;
    },
    { immediate: true, deep: true }
);
</script>

<style lang="scss" scoped>
.customer-detail {
    display: flex;
    justify-content: space-between;

    .left-module {
        flex: 0 0 310px;
        width: 310px;
        margin-right: 16px;
    }

    .right-module {
        flex: auto;
        width: calc(100vw - 576px);
        overflow: hidden;
    }

    .customer-card {
        margin-bottom: 16px;
        background: #fff;
        border: 1px solid #eaeaea;

        &:last-of-type {
            margin-bottom: 0;
        }
    }

    .journey-box {
        background: #fff;
        padding: 14px 20px 0;
        box-shadow: 0 1px 4px rgb(0 21 41 / 8%);
        margin-bottom: 14px;
        box-sizing: border-box;
        border: 1px solid #eaeaea;
        width: 100%;

        .title-box {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #eaeaea;
            padding-bottom: 14px;

            .lable-name {
                font-size: 16px;
            }
        }

        .base-info {
            display: flex;
            justify-content: space-between;

            .change-btn {
                display: flex;
                align-items: center;
                padding-left: 15px;
                border-radius: 2px;
                box-shadow: -7px 0 10px -7px rgb(0 0 0 / 12%);
            }
        }

        .step-box {
            white-space: nowrap;
            padding: 36px 0;

            & > div {
                font-size: 16px;
                font-family: STHeitiSC-Medium, STHeitiSC;
                font-weight: 500;
                color: #333;
                margin-right: 152px;
                display: inline-block;
                vertical-align: middle;
                position: relative;

                &::after {
                    content: '';
                    width: 140px;
                    height: 1px;
                    border-top: dashed 1px #ffc69e;
                    position: absolute;
                    top: 15px;
                    right: -146px;
                }

                &:last-child::after {
                    display: none;
                }
            }

            .icon-box {
                display: inline-block;
                vertical-align: middle;
                width: 30px;
                height: 30px;
                border-radius: 50%;
                font-size: 16px;
                font-family: STHeitiSC-Medium, STHeitiSC;
                font-weight: 500;
                color: #33302d;
                background: #eaeaea;
                text-align: center;
                line-height: 30px;
                margin-right: 8px;

                &.active {
                    color: white;
                    background: #ff6b00;
                }
            }

            span {
                vertical-align: middle;
            }
        }

        .step-box div:last-child {
            margin-right: 28px;
        }
    }

    .member-info-box {
        padding: 20px 16px;

        .member-info-title {
            padding-bottom: 4px;
            font-size: 16px;
            font-weight: 500;
            color: #33302d;
            line-height: 16px;
        }

        .member-info-cell {
            margin-top: 16px;
            display: flex;
            align-items: center;
            font-size: 14px;

            .cell-label {
                min-width: 70px;
                color: #969696;
            }

            .cell-label-tag {
                margin: 0 4px 4px 0;
            }

            .cell-value {
                span {
                    padding-left: 14px;
                    color: #ff6b00;
                    cursor: pointer;
                }
            }
        }
    }
}
</style>
